package com.example.homework.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.homework.models.SearchService
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

class MainViewModel : ViewModel() {
    private val searchService: SearchService = SearchService()

    private val _uiState: MutableStateFlow<UiState> = MutableStateFlow(UiState())
    val uiState: Flow<UiState> = _uiState.asStateFlow()

    private val _queryText: MutableStateFlow<String> = MutableStateFlow<String>("")
    val queryText: Flow<String> = _queryText.asStateFlow()

    private var inputText: String = ""

    fun updateInputText(text: String) {
        inputText = text
        checkInputLength()
    }

    fun searchQuery() {
        viewModelScope.launch {
            _uiState.update {
                it.copy(isButtonEnabled = false, isProgressBarVisible = true)
            }
            searchService.search()
            _queryText.emit(inputText)
            _uiState.update {
                it.copy(isButtonEnabled = true, isProgressBarVisible = false)
            }
        }
    }

    private fun checkInputLength() {
        _uiState.update {
            it.copy(isButtonEnabled = inputText.length > 3)
        }
    }
}